<?php

namespace App\Http\Controllers\Api;

use App\Models\Product;
use App\Models\SearchRecord;
use Illuminate\Http\Request;

class SearchRecordsController extends ApiController
{
    public function index()
    {
        $r_products = Product::where(['on_sale'=>1,'is_recommend'=>1])->get();
        $data['r_products'] = $r_products;
        $data['toplogs'] = $this->topSearchs();
        $data['mylogs'] = $this->mySearchLogs();
        return $this->success($data);
    }
    /**
     *
     * @return mixed
     */
    public function topSearchs()
    {
        $searchs = SearchRecord::select('keywords')->groupBy('keywords')->orderByRaw('SUM(num) desc')->take(10)->get();
        return $searchs;
    }

    public function mySearchLogs()
    {
        // 先获取当前登录的用户信息
        if (empty(auth('api')->user())) {
            return NUll;
        }
        $searchs = SearchRecord::select('keywords')->where('user_id',auth('api')->user()->id)->orderBy('num','desc')->take(10)->get();
        return $searchs;
    }

    public function search(Request $request)
    {
        $keyword = $request->keyword;
        if (!$keyword) {
            return $this->success('请输入搜索内容.','error');
        }
        //用户登录则记录
        if (auth('api')->user()) {
            $check = SearchRecord::where(['user_id'=>auth('api')->user()->id,'keywords'=>$keyword])->first();
            if ($check) {
                $check->num = intval($check->num)+1;
                $check->save();
            }else{
               $add = array();
               $add['user_id'] = auth('api')->user()->id;
               $add['keywords'] = $keyword;
               $add['num'] = 1;
               SearchRecord::create($add);
            }
        }
        $prolist = Product::where(['on_sale'=>1,['title','like','%'.$keyword.'%']])->orderBy('created_at','desc')->get();
        $data['prolist']= $prolist;
        return $this->success($data);
    }
}
